<?php
/**
 * smarty视图方案
 *
 * 实现了I-Framework和smarty的集成
 * 
 * 一个示例程序：
 * <code>
 * require "../../../smarty/Smarty.class.php";
 * 
 * class SmartyController extends IApplication {
 * 	public function init() {
 *      //设置smarty选项
 * 		IModelAndSmarty::setSmartyOptions(array("compile_check" => true,  
 * 											"smarty->debugging" => true, 
 * 											));
 * 	}
 * 	
 * 	public function appIndex() {
 * 		$this->text = 1000;
 * 		$this->array = array(1, 2, 3, 4, 5);
 * 		return new IModelAndSmarty($this, "index.tpl");//显示模板
 * 	}
 * }
  * </code>
 * 
 * @version $Id: IModelAndSmarty.php 312 2008-04-23 16:29:38Z iwind $
 * @package util.mvc
 * @since 0.0.2
 */
class IModelAndSmarty extends IAbstractViewScheme {
	/**
	 * Smarty对象
	 *
	 * @var Smarty
	 */
	private static $smarty;
	private $model;
	private $template;
	
	/**
	 * 构造器
	 *
	 * @param mixed $model 模型：IModel实例，array或者object
	 * @param string $template 模板名称，在smarty里通常为 *.tpl，比如 index.tpl
	 */
	public function __construct($model, $template) {
		$this->model = $model;
		$this->template = $template;
	}
	
	/**
	 * 设置smarty选项
	 *
	 * @param array $options smarty选项
	 */
	public static function setSmartyOptions(array $options) {
		self::$smarty = new Smarty();
		foreach ($options as $key=>$option) {
			if (native::isValidVariableName($key)) {
				self::$smarty->$key = $option;
			}
		}
	}
	
	/**
	 * 取得模型
	 *
	 * @return mixed
	 */
	public function getModel() {
		return $this->model;
	}
	
	/**
	 * 取得模板名称
	 *
	 * @return string
	 */
	public function getTemplate() {
		return $this->template;
	}
	
	/**
	 * 取得Smarty对象
	 *
	 * @return Smarty
	 */
	public function &getSmarty() {
		if (self::$smarty == null) {
			self::$smarty = new Smarty();
		}
		return self::$smarty;
	}
	
	/**
	 * 执行
	 *
	 */
	public function invoke() {
		$smarty = &$this->getSmarty();
		$template = $this->getTemplate();
		$model = $this->getModel();		
		if (is_object($model) && ($model instanceof IModel)) {
			foreach ($model->getObjectMap() as $name=>$object) {
				$smarty->assign($name, $object);
			}
		}
		else {
			if (is_array($model) || is_object($model)) {
				foreach ($model as $key=>$value) {
					if (native::isValidVariableName($key)) {
						$smarty->assign($key, $value);
					}
				}
			}
		}
		$smarty->display($template);
	}
	
	/**
	 * 添加键值对
	 *
	 * @param string $key 键
	 * @param string $value 值
	 * @since 0.1
	 */
	public function put($key, $value) {
		$this->getSmarty()->assign($key, $value);
	}
}

?>